from tqdm import tqdm
from mini_tools.cjjtool import killjc
import requests
import subprocess
import os

# 当前软件版本
current_version = '2.6.6'
win_version = 'ALL'

home = '198.12.127.45'
# 远程服务器上的版本信息
remote_version_url = f"http://{home}/version.txt"


# 检查是否有新版本可用
def check_for_update():
    try:
        response = requests.get(remote_version_url)
        remote_version = response.text.strip()
        if remote_version != current_version:
            return remote_version
    except Exception as e:
        print("检查更新时出错:", e)
    return False


# 下载并安装新版本
def update(new_version):
    try:

        old_exename = f"gt-{win_version}-{current_version.replace('.','_')}.exe"
        remote_exename = f"gt-{win_version}-{new_version.replace('.','_')}.exe"

        download_url = f"http://{home}/{remote_exename}"
        print(f'正在下载新版本:{download_url}...')

        response = requests.get(download_url, stream=True)

        # 获取文件大小
        file_size = int(response.headers.get("content-length", 0))

        # 使用 tqdm 创建进度条，并设置文件大小
        progress_bar = tqdm(total=file_size, unit="B", unit_scale=True)

        with open(remote_exename, "wb") as file:
            for data in response.iter_content(chunk_size=1024):
                file.write(data)
                progress_bar.update(len(data))

        # 关闭进度条
        progress_bar.close()

        # 替换旧版本
        print('更新完毕')
        subprocess.run(remote_exename, shell=True)
        print(old_exename)
        killjc(old_exename)

    except Exception as e:
        print("更新时出错:", e)


def del_old():
    paths = os.listdir('.')
    exenames = [path for path in paths if path.startswith(
        f'gt-{win_version}') and path.endswith('.exe')]
    exenames.sort()
    if len(exenames) >= 2:
        for j in range(len(exenames)-1):
            subprocess.run(["del", exenames[j]], shell=True)

def changeCog():
    import json
    with open('config.json','r',encoding='utf-8') as f:
        ccof=json.load(f)
    ccof['mbShopid']='1029704141'
    with open('config.json','w',encoding='utf-8') as f:
        json.dump(ccof,f)
    
def up000():
    changeCog()
    new_version = check_for_update()
    if check_for_update():
        print("发现新版本，开始更新...")
        update(new_version)
    else:
        print("当前是最新版本.")
        del_old()  # 删除旧版本
